package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public void add(Role role, Integer[] permissionIds, Integer[] menuids) {
        log.info("[角色-添加]data:{},permissionIds:{},menuids:{}",role,permissionIds,menuids);


        roleDao.add(role);

        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);

        }
        for (Integer menuid : menuids) {
            roleDao.insertRoleAndMenu(role.getId(),menuid);
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> page =roleDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {

        return roleDao.findById(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds, Integer[] menuids) {
        log.info("[角色-编辑]role:{},permissionIds:{},menuids{}",role,permissionIds,menuids);
        roleDao.edit(role);

        roleDao.deletePermissionByRoleId(role.getId());
        roleDao.deleteMenuByRoleId(role.getId());

        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);
        }

        for (Integer menuid : menuids) {
            roleDao.insertRoleAndMenu(role.getId(),menuid);
        }
    }

    @Override
    public void delById(Integer id) {


        long countPermission=roleDao.countPermissionByRoleId(id);
        long countMenu=roleDao.countMenuByRoleId(id);

        if (countPermission>=1 || countMenu>=1){
            throw new BusinessRuntimeException("该用户是有权限和菜单,不能删");
        }
        roleDao.deletePermissionByRoleId(id);
        roleDao.deleteMenuByRoleId(id);
        roleDao.deleteById(id);

    }
}
